<?php

namespace App\Admin\Extensions\Tools;

use Dcat\Admin\Admin;
use Dcat\Admin\Grid\Tools\AbstractTool;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Arr;

class TypeSelect extends AbstractTool
{

    private array $option;
    private mixed $default;

    public function __construct(array $option = [])
    {
        if (count($option)) {
            $this->option = $option;
        } else {
            $this->option = [
                //'hour' => '时段查看',
                'day' => '按日查看',
                'month' => '按月查看',
            ];
        }
        $this->default = request('type', Arr::first(array_keys($this->option)));
        parent::__construct();
    }


    protected function script(): string
    {
        $url = request()->fullUrlWithQuery(['type' => '_type_']);
        $option = $this->default;
        return <<<JS
$('input:radio.user-gender').change(function () {

    var url = "$url".replace('_type_', $(this).val());
    if ("$option" != $(this).val()) {
        var urlObj = new URL(url);
        var params = new URLSearchParams(urlObj.search);
        params.delete('date');
        params.delete('username');
        urlObj.search = params.toString();
        var newUrl = urlObj.toString();
        Dcat.reload(newUrl);
    }
});
JS;
    }

    public function render(): View|Factory|string|Application
    {
        Admin::script($this->script());
        $options = $this->option;
        $default = $this->default;

        return view('admin.tools.type', compact('options', 'default'));
    }
}
